package otcv.hr.util;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import otcv.hr.conf.Config;

public class SendMail {

	public SendMail() {

	}

	public static void postMail(MimeMessage msg, String recipient, String title, String sendMsg) {
		try {
			// Recipient
			InternetAddress[] address = { new InternetAddress(recipient) };

			msg.setHeader("content-type", "text/html;charset=utf-8");
			msg.setRecipients(Message.RecipientType.TO, address);
			msg.setSubject(title, "UTF-8");
			msg.setSentDate(new Date());

			MimeMultipart mp = new MimeMultipart();
			mp.setSubType("related");

			// html body.
			MimeBodyPart mbp1 = new MimeBodyPart();
			mbp1.setContent(sendMsg, "text/html;charset=UTF-8");
			mp.addBodyPart(mbp1);

			msg.setContent(mp);

			Transport.send(msg);
		} catch (Exception e) {

		}
	}

	public static MimeMessage setMailTemplate() throws Exception {
		// Properties Set
		Properties props = new Properties();
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.host", Config.getInstance().getString("mail.smtp.host"));
		props.put("mail.smtp.port", Config.getInstance().getString("mail.smtp.port"));

		Session session = Session.getInstance(props, new javax.mail.Authenticator() {
			@Override
			protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
				return new javax.mail.PasswordAuthentication(Config.getInstance().getString("mail.user.id"), Config.getInstance().getString("mail.user.pwd"));
			}
		});

		MimeMessage msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress(Config.getInstance().getString("mail.user.id"), Config.getInstance().getString("mail.user.name")));

		return msg;
	}
}